package lc20240522;

import lc20240521.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class Demo1 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(4);
        root.right = new TreeNode(8);
        root.left.left = new TreeNode(11);
        root.left.left.left = new TreeNode(7);
        root.left.left.right = new TreeNode(2);
        root.right.left = new TreeNode(13);
        root.right.right = new TreeNode(4);
        root.right.right.right = new TreeNode(1);
//        TreeNode root=new TreeNode(1);
//        root.left=new TreeNode(2);
        boolean b = hasPathSum1(root, 22);
        System.out.println(b);
    }

    //采用广度优先搜索的算法
    public static boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        Queue<Integer> sumQueue = new LinkedList<>();

        queue.add(root);
        sumQueue.add(root.val);
        while (!queue.isEmpty()) {
            TreeNode currentNode = queue.poll();
            int curSum = sumQueue.poll();
            if (currentNode.left==null&&currentNode.right==null){
                if (targetSum==curSum){
                    return true;
                }
            }
            if (currentNode.left != null) {
                queue.add(currentNode.left);
                sumQueue.add(currentNode.left.val + curSum);
            }
            if (currentNode.right != null) {
                queue.add(currentNode.right);
                sumQueue.add(currentNode.right.val + curSum);
            }
        }
        return false;
    }

    //采用递归的方法求解
    public static boolean hasPathSum1(TreeNode root,int targetSum){
        if (root==null){
            return false;
        }

        if (root.left==null&&root.right==null){
            return targetSum==root.val;
        }
        targetSum-=root.val;
        return hasPathSum1(root.left,targetSum)||hasPathSum1(root.right,targetSum);
    }
}
